package org.example.myleet.p1706;

public class Solution {
    public int[] findBall(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int[] result = new int[n];
        for (int i = 0; i < n; ++i) {
            result[i] = dfs(grid, m, n, 0, i);
        }
        return result;
    }

    private int dfs(int[][] grid, int m, int n, int row, int col) {
        if (row >= m) {
            return col;
        }
        int val = grid[row][col];
        if (col + val >= n || col + val < 0 || grid[row][col + val] == -val) {
            return -1;
        }
        return dfs(grid, m, n, row + 1, col + val);
    }
}
